package com.jzg.common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.jfinal.kit.PropKit;
import com.jzg.common.render.Result;


public class HttpUtil {
	
	private static final Logger logger = Logger.getLogger(HttpUtil.class.getName());
	
	public static final String  CASE_HTTP_URL = PropKit.use("app-config-dev.txt").get("CASE_HTTP_URL");
	private static  CookieStore cookieStore = new BasicCookieStore();
    static{
        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "00003u2yv9DmZEStMDAzHy8_yQO:17u1nlftv");
        cookie.setVersion(0);
        cookie.setDomain("10.166.196.200");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);    	
    }

	
    private static final RequestConfig requestConfig = RequestConfig.custom()
    		.setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
    		.setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();

    /**
     * 发送Get请求
     * @param url
     * @return
     */
    public static Result doGet(String url) {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)//设置Cookie
                .build();
        
    	logger.info(String.format("发送GET请求：%s", url));
    	HttpGet httpGet = new HttpGet(url);
    	httpGet.setConfig(requestConfig);
    	CloseableHttpResponse response=null;
        try {
        	httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36");
        	
        	response = httpClient.execute(httpGet);
            if(response!=null) {
            	int code=response.getStatusLine().getStatusCode();
                if (code == HttpStatus.SC_OK) {
                    return new Result(code,"请求成功",EntityUtils.toString(response.getEntity()));
            	}else {
            		return new Result(code,"");
            	}
            }else {
            	return new Result("-1","请求无响应！");
            }
        } 
        catch (IOException e) {
        	logger.error("发送GET请求异常", e);
        	return new Result("500",e.getMessage());
        }finally {
        	if(response!=null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}        		
        	}
            try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
    
    /**
     * 提交表单信息
     * @param url
     * @param paramsMap
     * @return
     */
    public static Result doPostForForm(String url, Map<String, Object> paramsMap){
    	
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)//设置Cookie
                .build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : paramsMap.keySet()) {
            nvps.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
        }
        
        CloseableHttpResponse response=null;
        try {
        	
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36");

            logger.info(String.format("发送Post请求：%s", EntityUtils.toString(httpPost.getEntity())));
        	response = httpClient.execute(httpPost);
            int code=response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                return new Result(true,"请求成功",EntityUtils.toString(response.getEntity()));
        	}else {
        		return new Result(false,"请求接口失败【"+code+"】！");
        	}
        } catch (Exception e) {
        	logger.error("发送POST请求异常", e);
            return new Result(false,"调用接口异常！",e.getMessage());
        }finally {
            if(null != response){
                try {
                	response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
    }
    
    /**
     * post json请求
     * @param url
     * @param jsonParams
     * @return
     */
    public static Result doPostForJson(String url, String jsonParams){
    	
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)//设置Cookie
                .build();
    	
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type","application/json");
        CloseableHttpResponse response=null;
        try {
            httpPost.setEntity(new StringEntity(jsonParams,ContentType.create("application/json", "utf-8")));
        	logger.info(String.format("发送Post请求：%s", EntityUtils.toString(httpPost.getEntity())));
            response = httpClient.execute(httpPost);
            
        	int code=response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                return new Result(code,"请求成功",EntityUtils.toString(response.getEntity()));
        	}else {
        		return new Result(code,"");
        	}
        } catch (Exception e) {
        	logger.error("发送POST请求异常", e);
            return new Result(500,e.getMessage());
        }finally {
            if(null != response){
                try {
                	response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
    } 
    
    
	
	public static void getVerifyCode(String url){
		
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)//设置Cookie
                .build();
        
    	logger.info(String.format("发送GET请求：%s", url));
    	HttpGet httpGet = new HttpGet(url);
    	httpGet.setConfig(requestConfig);
    	CloseableHttpResponse response=null;
        try {
        	httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36");
        	
        	response = httpClient.execute(httpGet);
            if(response!=null) {
            	int code=response.getStatusLine().getStatusCode();
                if (code == HttpStatus.SC_OK) {
                	
        			InputStream inStream = response.getEntity().getContent();
        			//得到图片的二进制数据，以二进制封装得到数据，具有通用性
        			byte[] data = readInputStream(inStream);
        			//new一个文件对象用来保存图片，默认保存当前工程根目录
        			File imageFile = new File("d:/code.jpg");
        			//创建输出流
        			FileOutputStream outStream = new FileOutputStream(imageFile);
        			//写入数据
        			outStream.write(data);
        			//关闭输出流
        			outStream.close();
            	}else {
            	}
            }else {
            }
        } 
        catch (IOException e) {
        	logger.error("发送GET请求异常", e);
        }finally {
        	if(response!=null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}        		
        	}
            try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
    
	public static byte[] readInputStream(InputStream inStream){
		
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			//创建一个Buffer字符串
			byte[] buffer = new byte[1024];
			//每次读取的字符串长度，如果为-1，代表全部读取完毕
			int len = 0;
			//使用一个输入流从buffer里把数据读取出来
			while( (len=inStream.read(buffer)) != -1 ){
				//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
				outStream.write(buffer, 0, len);
			}
			//关闭输入流
			inStream.close();
			//把outStream里的数据写入内存
			return outStream.toByteArray();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	
	
	/**
	 * 发送GET请求
	 * 
	 * @param url
	 * @return
	 */
	public static Result sendGet(String url) {
		Result result = new Result();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
				.setConnectionRequestTimeout(5000) // 设置请求超时时间
				.setSocketTimeout(5000).setRedirectsEnabled(true)// 默认允许自动重定向
				.build());
		//设置请求的报文头部的编码
		httpGet.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
		//设置期望服务端返回的编码
		httpGet.setHeader(new BasicHeader("Accept", "application/json;charset=utf-8"));
		httpGet.setHeader(new BasicHeader("connection", "Keep-Alive"));
		httpGet.setHeader(new BasicHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"));
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			if (httpResponse != null) {
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					return new Result(true, "请求成功！", EntityUtils.toString(httpResponse.getEntity()));
				} else {
					return new Result(false, "错误代码【" + httpResponse.getStatusLine().getStatusCode() + "】！",EntityUtils.toString(httpResponse.getEntity()));
				}
			} else {
				result.setCode(false);
				result.setMsg("请求无响应，请稍后再试！");
			}
		} catch (IOException e) {
			result.setCode(false);
			result.setMsg("请求异常，请稍后再试!");
			result.setData(e.getMessage());
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * 调用 API
	 * 
	 * @param parameters
	 * @return
	 */
	public static Result doPost(String url, String parameters) {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);
		post.setConfig(requestConfig);

		try {
			post.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
			//设置期望服务端返回的编码
			post.setHeader(new BasicHeader("Accept", "application/json;charset=utf-8"));
			post.setHeader(new BasicHeader("connection", "Keep-Alive"));
			post.setHeader(new BasicHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"));
			
			post.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
			HttpResponse httpResponse = httpclient.execute(post);
			if(httpResponse==null) {
				return new Result(false,"接口无响应！");
			}
			
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				return new Result(true, "请求成功！", EntityUtils.toString(httpResponse.getEntity()));
			}else {
				return new Result(false, "错误代码【" + httpResponse.getStatusLine().getStatusCode() + "】！",EntityUtils.toString(httpResponse.getEntity()));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"生成支付码异常!",e.getMessage());
		}finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	

    
	public static void main(String[] args) {
		
	}
    

}
